package com.baomidou.springmvc.interceptor;

import java.io.IOException;
import java.lang.reflect.Method;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.alibaba.fastjson.JSON;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.springmvc.common.utils.AddressUtils;
import com.baomidou.springmvc.common.utils.IpAdrressUtil;
import com.baomidou.springmvc.model.system.Log;
import com.baomidou.springmvc.model.system.User;
import com.baomidou.springmvc.service.system.ILogService;
import com.hazelcast.logging.ILogger;
import com.hazelcast.logging.Logger;


/**
 * 
 * @author hewei
 * @ClassName: SystemLogAspect
 * @Copyright beauty_tech
 * @date 2018年2月5日 上午11:07:44
 * @description 捕获系统日志 待优化点:加入队列
 */
@Aspect
@Component
public class SystemLogAspect {

	@Autowired
	private ILogService logService;
	//@Resource(name="producer")  
	//@Autowired
   // private RmqProducer rmqProducer; 
	private static ILogger logger = Logger.getLogger(SystemLogAspect.class);
	@Pointcut("@annotation(com.baomidou.springmvc.interceptor.MethodLog)")
	public void methodAspect() {
	}

	@Before("methodAspect()")
	public void doBefore(JoinPoint joinPoint) throws  IOException {
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
				.getRequest();
		HttpSession session = request.getSession();
		User u = null;
		if(session.getAttribute("userVo") instanceof User){
			 u = (User) session.getAttribute("userVo");
		}
		
		// 请求的IP
		String ip = IpAdrressUtil.getIpAdrress(request);
		
		// 获取用户请求方法的参数并序列化为JSON格式字符串
		String params = "";
		if (joinPoint.getArgs() != null && joinPoint.getArgs().length > 0) {
			for (int i = 0; i < joinPoint.getArgs().length; i++) {

					params += joinPoint.getArgs()[i] + ";";

			}
		}

//		System.out.println("params.length()-------------------"+params.length());
		
		Log log = new Log();
		log.setCreatetime(System.currentTimeMillis());
		log.setDescribe(getControllerMethodDescription(joinPoint));
		log.setIp(ip);
		log.setIpresion(AddressUtils.getAddresses(ip));
		log.setMethod(joinPoint.getTarget().getClass().getName() + "." + joinPoint.getSignature().getName() + "()");
		log.setParams(JSON.toJSONString(params));
		log.setType(0);//请求
		if(u!=null){
			log.setUsername(u.getName());
		}
		//rmqProducer.sendMessage(log);
		logService.insert(log);
	}

	@AfterThrowing(pointcut = "methodAspect()", throwing = "e")
	public void doAfterThrowing(JoinPoint joinPoint, Throwable e) throws  IOException {
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
				.getRequest();
		HttpSession session = request.getSession();
		User u = null;
		if(session.getAttribute("userVo") instanceof User){
			 u = (User) session.getAttribute("userVo");
		}
		
		// 请求的IP
		//String ip = request.getRemoteAddr();经过多次代理后获取不到用户的真实ip
		String ip = IpAdrressUtil.getIpAdrress(request);

		// 获取用户请求方法的参数并序列化为JSON格式字符串
		String params = "";
		if (joinPoint.getArgs() != null && joinPoint.getArgs().length > 0) {
			for (int i = 0; i < joinPoint.getArgs().length; i++) {
				logger.info("===============joinPoint.getArgs()[i]"+joinPoint.getArgs()[i]);

					params += JSONArray.toJSONString(joinPoint.getArgs()[i]) + ";";

				
			}
		}
	
		Log log = new Log();
		log.setCreatetime(System.currentTimeMillis());
		log.setDescribe(getControllerMethodDescription(joinPoint));
		log.setIp(ip);
		log.setIpresion(AddressUtils.getAddresses(ip));
		log.setMethod(joinPoint.getTarget().getClass().getName() + "." + joinPoint.getSignature().getName() + "()");
		log.setParams(JSON.toJSONString(params));
		log.setType(1);//异常类别
	    if(u!=null){
		log.setUsername(u.getName());
	    }
	
		log.setExceptioncode(e.getClass().getName());
        log.setExceptiondetail(e.getMessage());
        //rmqProducer.sendMessage(log);
		logService.insert(log);
	}

	/**
	 * 获取注解中对方法的描述信息 用于Controller层注解
	 * 
	 * @param joinPoint
	 *            切点
	 * @return 方法描述
	 * @throws Exception
	 */
	@SuppressWarnings("rawtypes")
	public static String getControllerMethodDescription(JoinPoint joinPoint) {
		String targetName = joinPoint.getTarget().getClass().getName();
		String methodName = joinPoint.getSignature().getName();
		Object[] arguments = joinPoint.getArgs();
		Class targetClass = null;
		try {
			targetClass = Class.forName(targetName);
		} catch (Exception e) {
			e.printStackTrace();
		}
		Method[] methods = targetClass.getMethods();
		String description = "";
		for (Method method : methods) {
			if (method.getName().equals(methodName)) {
				Class[] clazzs = method.getParameterTypes();
				if (clazzs.length == arguments.length) {
					description = method.getAnnotation(MethodLog.class).description();
					break;
				}
			}
		}
		return description;
	}
}
